package com.mayflygeek.mayflyask.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author 蝈蝈 
 * @email guodefu909@126.com
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * MD5工具类
 */
public class MD5Utils {
	
	private static Logger log = LoggerFactory.getLogger(MD5Utils.class);

	private static final String[] digits = { "0", "1", "2", "3", "4", "5", "6",
			"7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	private MD5Utils() {
	}
	
	/**
	 * 获取随机字符，只包含数字和大小写字母
	 * @param length
	 * @return
	 */
	public static String getRandomCharacters(int length) {
		
		StringBuilder result = new StringBuilder();
		Random random = new Random();
		for(int i = 0; i < length; i++) {
			int type = random.nextInt(3);
			if (type == 0 ) {
				result.append(random.nextInt(9));
			}else if(type == 1 ){
				result.append((char)(random.nextInt(26) + 65));
			}else {
				result.append((char)(random.nextInt(26) + 97));
			}
		}
		return result.toString();
	}

	public static String encode(String data) {
		if (data != null) {
			MessageDigest md5 = null;
			try {
				md5 = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException e) {
				log.error("没有此加密算法！");
				log.error(e.getMessage(), e);
			}
			if (md5 != null) {
				md5.update(data.getBytes());
				return toHexString(md5.digest());
			}
		}
		return data;
	}

	private static String toHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(toHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String toHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return digits[d1] + digits[d2];
	}

}
